import { Form, Input } from 'antd';
import React, { useState, useCallback } from 'react';
import styles from './PasswordValidate.less';

/**
 * @description: 表单密码添加的校验
 * @param {formLayout, form}
 * @return: React Node
 */
const PasswordValidate = function PasswordValidate(props) {
  const { form, formLayout } = props;
  const { getFieldDecorator, getFieldValue } = form;

  const [complexity, setComplexity] = useState(0);
  const computedComplexity = val => {
    let res = 0;
    if (/[0-9]+/.test(val)) res += 1;
    if (/[a-z]+/.test(val)) res += 1;
    if (/[A-Z]+/.test(val)) res += 1;
    // eslint-disable-next-line no-useless-escape
    if (/[\$\+\(\)\*\.\?\^~!@#%&_]+/.test(val)) res += 1;
    return res;
  };

  const onChange = useCallback(evt => {
    setComplexity(computedComplexity(evt.target.value));
  }, []);

  return (
    <>
      <Form.Item {...formLayout} label="新密码">
        {getFieldDecorator('password', {
          onChange: onChange,
          rules: [
            {
              required: true,
              message: '请输入新密码',
            },
            {
              async validator(_, val) {
                if (val && (val.length < 8)) {
                  throw new Error('长度需要大于等于8位');
                }
                if (val && (val.length > 16)) {
                  throw new Error('长度需要小于等于16位');
                }
                if (/\s+/.test(val)) {
                  throw new Error('密码不能包含空格！');
                }
                if (/[^\$\+\(\)\*\.\?\^~!@#%&_A-Za-z0-9]/.test(val)) {
                  throw new Error('密码不能包含特殊字符, 只支持 $+()*.?^~!@#%&_');
                }
                if (computedComplexity(val) < 2) {
                  throw new Error('密码必须由数字，大写字母，小写字母，字符任意两种组成');
                }
                return val;
              },
            },
          ],
        })(<Input.Password size="large" maxLength={16} placeholder="请输入新密码" allowClear />)}
        <ul className={`${styles.complexity} is-complexity-${complexity}`}>
          <li />
          <li />
          <li />
        </ul>
        {['', '弱', '弱', '中', '强'][complexity]}
      </Form.Item>
      <Form.Item {...formLayout} label="确认新密码">
        {getFieldDecorator('checkPassword', {
          rules: [
            {
              required: true,
              message: '请再次输入新密码',
            },
            {
              async validator(_, val) {
                if (val !== getFieldValue('password')) {
                  throw new Error('两次输入的密码不相同');
                }
                return val;
              },
            },
          ],
        })(
          <Input.Password
            visibilityToggle={false}
            size="large"
            placeholder="请输入确认新密码"
            allowClear
          />,
        )}
      </Form.Item>
    </>
  );
};

export default PasswordValidate;
